use diesel::prelude::*;
use diesel::MysqlConnection;

use super::model::*;
use crate::database::{crud, schema::tag, DbError};
use crate::db_read;
use crate::db_read_id_in;
use crate::{
    db_create, db_delete, db_read_by_field, db_read_count_from_offset,
    db_read_count_from_offset_by_field, db_update,
};

db_create!(tag, Tag, NewTag, create);
db_read!(tag, Tag, read_id);
db_read_id_in!(tag, Tag, read_id_in);
db_read_by_field!(tag, Tag, read_by_slug, slug, String);
db_read_count_from_offset!(tag, Tag, read_count_from_offset);
db_read_count_from_offset_by_field!(tag, Tag, read_count_from_offset_by_cid, cid, i32);
db_update!(tag, NewTag, update);
db_delete!(tag, delete);

#[cfg(test)]
mod tests {
    use super::*;
    use crate::{
        database::{self, establish_connection, table::category::model::NewCategory},
        db_read, test_db_create, test_db_delete, test_db_read, test_db_update,
    };
    use diesel::Connection;

    db_read!(tag, Tag, read);

    fn insert_test_data(conn: &mut MysqlConnection) -> (i32, i32, i32) {
        let category_id = database::table::category::crud::create(
            conn,
            NewCategory {
                name: "CATE",
                desc: "DESC",
                cover: "COVER",
                slug: "LINK",
            },
        )
        .unwrap();
        let tag_id1 = create(
            conn,
            NewTag {
                name: "TAG1",
                desc: "DESC1",
                avatar: "AVATAR1",
                slug: "LINK1",
                cid: category_id,
            },
        )
        .unwrap();
        let tag_id2 = create(
            conn,
            NewTag {
                name: "TAG2",
                desc: "DESC2",
                avatar: "AVATAR2",
                slug: "LINK2",
                cid: category_id,
            },
        )
        .unwrap();
        (tag_id1, tag_id2, category_id)
    }

    test_db_create!();
    test_db_read!();
    test_db_update!(name, "NEW_TAG".to_string());
    test_db_delete!();
}
